package com.gopay.scheduler.service.cbrmb.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gopay.common.constants.proccode.ProcCodeConstants;

import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.cps.dao.cbrmb.CbRmbIntlCardDishonorDAO;
import com.gopay.common.cps.dao.cbrmb.CbRmbWildCardAssistDtlDAO;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.domain.cbrmb.internationalcard.CbRmbIntlCardDishonor;
import com.gopay.common.domain.cbrmb.internationalcard.CbRmbWildCardAssistDtl;
import com.gopay.common.domain.cbrmb.internationalcard.masapay.MasaPayQueryOrderDTO;
import com.gopay.common.domain.cbrmb.internationalcard.masapay.MasaPayQueryOrderDTOReq;
import com.gopay.common.domain.cbrmb.internationalcard.masapay.MasaPayQueryOrderDTOResp;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.cbrmb.MasaPayRemoteService;
import com.gopay.remote.cps.cbrmb.CbrmbMasaPayCallbackRemoteService;
import com.gopay.scheduler.service.cbrmb.CbRmbIntlCardService;
import com.ibm.icu.util.Calendar;

/**
 * 
 * @ClassName: CbRmbIntlCardServiceImpl
 * @Description: TODO
 * @author gd.cui
 * @date 2017年12月11日 下午2:47:14
 */
@Service(value = "cbRmbIntlCardService")
public class CbRmbIntlCardServiceImpl implements CbRmbIntlCardService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "cbRmbWildCardAssistDtlDAO")
	private CbRmbWildCardAssistDtlDAO cbRmbWildCardAssistDtlDAO;

	@Resource(name = "masaPayRemoteServiceClient")
	private MasaPayRemoteService masaPayRemoteService;

	@Resource(name = "cbRmbIntlCardDishonorDAO")
	private CbRmbIntlCardDishonorDAO cbRmbIntlCardDishonorDAO;

	@Resource(name = "cbrmbMasaPayCallbackClient")
	private CbrmbMasaPayCallbackRemoteService cbrmbMasaPayCallbackRemoteService;

	@Resource(name = "cpsGeneralMainOrderDAO")
	private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;


	@Override
	public void checkOrder(CbRmbWildCardAssistDtl order) {
		logger.info(String.format("international card orderId:%s,check order count:%s", order.getGopayOrderId(),
				order.getCheckCount()));
		order.setCheckCount(order.getCheckCount() + 1);
		cbRmbWildCardAssistDtlDAO.update(order);
		MasaPayQueryOrderDTOReq req = new MasaPayQueryOrderDTOReq();
		req.setMerchantOrderNo(order.getGopayOrderId());
		MasaPayQueryOrderDTOResp resp = null;
		try {
			resp = masaPayRemoteService.queryOrder(req);
		} catch (GopayException e) {
			logger.error("请求bis masapay异常:" + e);
		}
		// 根据返回的结果处理，status S-成功 F-失败别的状态还不明确
		if (resp != null && resp.getList().size() > 0) {
			MasaPayQueryOrderDTO queryOrder = resp.getList().get(0);
			CbRmbWildCardAssistDtl newOrder = cbRmbWildCardAssistDtlDAO.findByGopayOrderId(order.getGopayOrderId());
			CpsGenMainOrder main = cpsGeneralMainOrderDAO.findByGopayOrderId(order.getGopayOrderId());
			if ("S".equalsIgnoreCase(queryOrder.getStatus())) {
				if ("00".equals(newOrder.getWildCardPayStatus())|| "12".equals(newOrder.getWildCardPayStatus())) {
					newOrder.setWildCardPayStatus("10");
					newOrder.setUpdateTime(new Date());
					cbRmbWildCardAssistDtlDAO.update(newOrder);
				}
				if (main != null && 30000 == main.getTxnStaCd() && ("01740").equals(main.getGopayIntTxnCd())) {
					cbrmbMasaPayCallbackRemoteService.updateMainOrderTxnStaCd(order.getGopayOrderId(),
							TxnStaCode.TXN_STA_CD_30402.value);
				}
			} else if ("F".equalsIgnoreCase(queryOrder.getStatus())) {
				if ("00".equals(newOrder.getWildCardPayStatus()) || "12".equals(newOrder.getWildCardPayStatus())) {
					newOrder.setWildCardPayStatus("11");
					newOrder.setUpdateTime(new Date());
					cbRmbWildCardAssistDtlDAO.update(newOrder);
				}
				if (main != null && 30000 == main.getTxnStaCd()  && ("01740").equals(main.getGopayIntTxnCd())) {
					cbrmbMasaPayCallbackRemoteService.updateMainOrderTxnStaCd(order.getGopayOrderId(),
							TxnStaCode.TXN_STA_CD_20001.value);
				}
			} else {
				logger.info("返回的状态不明确，不处理暂时,订单号:{}", order.getGopayOrderId());
			}
		} else {
			logger.info("返回的结果有问题，不处理！");
		}
	}

	@Override
	public List<String[]> getIntlDishonorOrders() {
		List<String[]> orderList = new ArrayList<String[]>();
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -7);
		Date date = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String hql = " from CbRmbIntlCardDishonor t where t.appealStatus = '07' and t.dishonorTime<=to_date(:date,'yyyy-MM-dd hh24:mi:ss') and t.fundStatus = '03' ";
		Map<String, Object> param = new HashMap<>(1);
		param.put("date",sdf.format(date));
		List<CbRmbIntlCardDishonor> order = cbRmbIntlCardDishonorDAO.findByHql(hql, param);
		if (order != null && order.size() > 0) {
			for (CbRmbIntlCardDishonor dis : order) {
				orderList.add(new String[] { dis.getDishonorOrderId() });
			}
		}
		return orderList;
	}
	
	//冻结保证金180天后解冻  start
	@Override
	public List<String> getIntlCardFrozenDepositOrders() {
		List<String> orderList = new ArrayList<String>();
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -180);
		Date date = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String hql="from CpsGenMainOrder t where t.gopay_int_txn_cd='01740' and t.TRAN_FINISH_TIME <='"
				+sdf.format(date)+"'";
		Map<String,Object> param = new HashMap<String,Object>();
		List<CpsGenMainOrder>  orders = cpsGeneralMainOrderDAO.findByHql(hql, param);
		if(orders!=null&&orders.size()>0){
			for(CpsGenMainOrder ord : orders){
				orderList.add(ord.getGopayOrderId());
			}
		}
		return orderList;
	}


	@Override
	public List<String[]> getDishonorOrders() {
		List<String[]> orderList = new ArrayList<String[]>();
		DetachedCriteria criteria = DetachedCriteria.forClass(CbRmbIntlCardDishonor.class);
		criteria.add(Restrictions.in("fundStatus", new String[] { "02", "04" }));
		List<CbRmbIntlCardDishonor> list = cbRmbIntlCardDishonorDAO.findByCriteria(criteria);
		if (list != null && list.size() > 0) {
			for (CbRmbIntlCardDishonor dis : list) {
				orderList.add(new String[] { dis.getDishonorOrderId() });
			}
		}
		return orderList;
	}

	@Override
	public void paySettle(CbRmbWildCardAssistDtl order) {
		try {
			cbrmbMasaPayCallbackRemoteService.masaPayReturnUpdateOrder(order.getGopayOrderId());
			String result = cbrmbMasaPayCallbackRemoteService.masaPayReturnFinishOrder(order.getGopayOrderId());
			if (ProcCodeConstants.PROC_CODE_000S1000.equals(result)
					|| ProcCodeConstants.PROC_CODE_100S1000.equals(result)) {
				cbrmbMasaPayCallbackRemoteService.frezDepositAmt(order.getGopayOrderId());
				cbrmbMasaPayCallbackRemoteService.notifyMer(order.getGopayOrderId());
			}
		} catch (GopayException e) {
			logger.error("请求cps masapay异常:" + e);
		}

	}

	

	
}
